package cn.iocoder.yudao.module.blog.controller.app.space;

import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.module.blog.controller.admin.space.vo.BlogSpaceCreateReqVO;
import cn.iocoder.yudao.module.blog.controller.admin.space.vo.BlogSpacePageReqVO;
import cn.iocoder.yudao.module.blog.controller.admin.space.vo.BlogSpaceRespVO;
import cn.iocoder.yudao.module.blog.controller.app.space.vo.AppBlogSpaceRespVO;
import cn.iocoder.yudao.module.blog.convert.space.BlogSpaceConvert;
import cn.iocoder.yudao.module.blog.dal.dataobject.space.BlogSpaceDO;
import cn.iocoder.yudao.module.blog.service.space.BlogSpaceService;
import cn.iocoder.yudao.module.member.api.user.MemberUserApi;
import cn.iocoder.yudao.module.member.api.user.dto.MemberUserRespDTO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Map;
import java.util.Set;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertSet;

@Tag(name = "用户 APP - 动态")
@RestController
@RequestMapping("/blog/space")
@Validated
public class AppSpaceController {

    @Resource
    private BlogSpaceService blogSpaceService;

    @Resource
    private MemberUserApi memberUserApi;

    @PostMapping("/create")
    @Operation(summary = "创建帖子")
    public CommonResult<Long> createSpace(@Valid @RequestBody BlogSpaceCreateReqVO createReqVO) {
        return success(blogSpaceService.createSpace(createReqVO));
    }

    @GetMapping("/page")
    @Operation(summary = "获得帖子分页")
    public CommonResult<PageResult<AppBlogSpaceRespVO>> getPostPage(@Valid BlogSpacePageReqVO pageVO) {
        PageResult<BlogSpaceDO> pageResult = blogSpaceService.getSpacePage(pageVO);

        // 查询用户信息
        Set<Long> memberIds = convertSet(pageResult.getList(), BlogSpaceDO::getMemberId);
        Map<Long, MemberUserRespDTO> memberMap = memberUserApi.getUserMap(memberIds);

        return success(BlogSpaceConvert.INSTANCE.convertAppPage(pageResult, memberMap));
    }

    @GetMapping("/get")
    @Operation(summary = "获得动态")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    public CommonResult<BlogSpaceRespVO> getSpace(@RequestParam("id") Long id) {
        BlogSpaceDO space = blogSpaceService.getSpace(id);
        MemberUserRespDTO memberUserRespDTO = memberUserApi.getUser(space.getMemberId());
        return success(BlogSpaceConvert.INSTANCE.convertApp(space, memberUserRespDTO));
    }
}
